/** @jsxImportSource react */

import { Button } from '~/components/react/shadcn/ui/button';
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '~/components/react/shadcn/ui/dialog';
import { Input } from '~/components/react/shadcn/ui/input';
import { useEffect, useState } from 'react';
import AlertMessage from '~/components/react/ui/AlertMessage';

type UpdateCollectionProps = {
  onUpdate: (id: bigint, title: string) => Promise<void>;
  onOpenChange: (open: boolean) => void;
  id: bigint;
  title: string;
  open: boolean;
};

export default function CollectionUpdator(props: UpdateCollectionProps) {
  const { onUpdate, onOpenChange, open, id } = props;
  const [title, setTitle] = useState(props.title);
  const [error, setError] = useState<string>('');

  useEffect(() => {
    setTitle(props.title);
  }, [id, props.title]);

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>修改分类</DialogTitle>
        </DialogHeader>
        <div>
          <Input
            value={title}
            onChange={(e) => {
              setTitle(e.target.value);
              setError('');
            }}
            placeholder="分类名称"
          />
          {error && <AlertMessage title="保存分类失败" description={error} />}
        </div>
        <DialogFooter>
          <Button
            onClick={async () => {
              if (title) {
                try {
                  await onUpdate(id, title);
                } catch (e) {
                  setError((e as Error).message || '未知错误');
                }
              }
            }}
          >
            保存
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
